package com.xiaoxu.springboot.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@WebListener
public class LoginListener implements ServletContextListener {
    private final static Logger LOGGER = LoggerFactory.getLogger(LoginListener.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        LOGGER.debug("====init listener===");
        //获取日志文件夹，判断是否存在，不存在直接返回
        File file=new File("/log");
        if (file==null || !file.exists()){
            return;
        }
        //获取当前时间字符串
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String currentDate = dtf.format(LocalDateTime.now());

        //获取/var/log下的日志列表，循环判断文件名称是否存在日期字符串，不包含则删除
        File[] files=file.listFiles();
        for (File temp:files) {
            String fileName=temp.getName();if (!fileName.contains(currentDate)){
                temp.delete();
            }
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        LOGGER.debug("===Destory listener");
    }
}
